package com.feicheng.service.a;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import com.feicheng.common.constant.Constant;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.task.Cache;
import com.feicheng.common.util.StringGenerator;
import com.feicheng.persistence.entity.*;

import com.feicheng.persistence.mapper.*;
import com.feicheng.persistence.model.KcWithJlModel;
import com.feicheng.persistence.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FFjService {

    @Autowired
    IAstoreService storeService;

    @Autowired
    IAroomService roomService;

    @Autowired
    IAmenjinService menjinService;

    @Autowired
    IAroomhourlypricesService hourpriceService;

    @Autowired
    IAroomdailypricesService dailypriceService;

    @Autowired
    IAroommonthlypricesService monthlypriceService;

    @Autowired
    IAroomyyjlService aroomyyjlService;

    @Autowired
    IAjiaolianService ajiaolianService;

    @Autowired
    IAkechengService akechengService;

    @Autowired
    IAkechengitemService kechengitemService;

    @Autowired
    IAroompjService roompjService;

    @Autowired
    Cache cache;

    @Transactional
    public JSONObject importFj(JSONObject param) {
        JSONObject mds = cache.getJSONObject("mdsname");
        JSONObject dict = cache.getJSONObject("dict");
        JSONObject tpDict = dict.getJSONObject("ROOMTP");
        JSONObject funcDict = dict.getJSONObject("ROOMFUNC");

        JSONObject hpp = new JSONObject();
        hpp.put("roomid", "temp");
        hpp = this.getprices(hpp);
        List<Aroomhourlyprices> aroomhourlyprices = hpp.getObject("aroomhourlyprices", new TypeReference<List<Aroomhourlyprices>>() {});
        if (null == aroomhourlyprices || aroomhourlyprices.size() == 0) {
            throw new SystemException("取得价格区间失败");
        }

        JSONArray asr = param.getJSONArray("fjs");
        int total = asr.size();
        param.put("total", total);
        int error = 0;
        int success = 0;
        for (int index = 0; index < asr.size(); index++) {
            JSONObject ar = asr.getJSONObject(index);
            String sname = ar.getString("sname");
            if (!mds.containsKey(sname)) {
                log.error("无法找到门店"+sname);
                log.error(mds.toJSONString());
                error++;
                continue;
            }

            Astore md = mds.getObject(sname, Astore.class);

            String rname = ar.getString("rname");
            if (!StringUtils.hasLength(rname)) {
                error++;
                continue;
            }
            Integer mj = ar.getInteger("mj");
            Integer rnrs = ar.getInteger("rnrs");
            Integer yjds = ar.getInteger("yjds");
            String imgs = ar.getString("imgs");
            String cover = ar.getString("cover");
            String tp = ar.getString("tp");
            if (!tpDict.containsKey(tp)) {
                log.error("无法找到房间类型"+tp);
                error++;
                continue;
            }
            Dict tpd = tpDict.getObject(tp, Dict.class);
            String func = ar.getString("func");
            if (!funcDict.containsKey(func)) {
                log.error("无法找到房间功能"+func);
                error++;
                continue;
            }
            Dict funcd = funcDict.getObject(func, Dict.class);

            Aroom room = new Aroom();
            room.setRoomid(StringGenerator.getID("JRM"));
            room.setStoreid(md.getStoreid());
            room.setRname(rname);
            room.setMj(mj);
            room.setRnrs(rnrs);
            room.setYjds(yjds);
            room.setCover(cover);
            JSONArray imgar = new JSONArray();
            if (StringUtils.hasLength(imgs)) {
                String[] imga = imgs.split(",");
                for (String s : imga) {
                    imgar.add(s);
                }
            }
            room.setImgs(imgar);
            room.setTp(tpd.getCode());
            room.setFunc(funcd.getCode());
            room.setRate(5.0f);
            roomService.save(room);

            List<Aroomhourlyprices> hps = new ArrayList<>();
            for (int jndex = 0; jndex < aroomhourlyprices.size(); jndex++) {
                Aroomhourlyprices aroomhourlyprice = aroomhourlyprices.get(jndex);
                Aroomhourlyprices hp = new Aroomhourlyprices();
                String kid = "";
                int xndex = jndex + 1;
                if (xndex < 10) {
                    kid = "0"+xndex;
                } else {
                    kid = ""+xndex;
                }
                hp.setHid(new StringBuilder("HP").append(LocalDateTime.now().format(Constant.full)).append(kid).toString());
                hp.setRoomid(room.getRoomid());
                hp.setStu(true);
                hp.setSt(aroomhourlyprice.getSt());
                hp.setEt(aroomhourlyprice.getEt());
                hp.setPrice(aroomhourlyprice.getPrice());
                hps.add(hp);
            }
            hourpriceService.saveBatch(hps);
            success++;
        }

        param.put("success", success);
        param.put("error", error);
        return param;
    }


    /**
     * 查询时段价格
     * @param param
     * @return
     */
    public JSONObject getprices(JSONObject param) {
        QueryWrapper<Aroomhourlyprices> qw = new QueryWrapper<>();
        QueryWrapper<Aroomdailyprices> qwdl = new QueryWrapper<>();
        QueryWrapper<Aroommonthlyprices> qwmt = new QueryWrapper<>();
        String roomid = param.getString("roomid");

        if (StringUtils.hasLength(roomid)) {
            qw.eq("roomid", roomid);
            qwdl.eq("roomid", roomid);
            qwmt.eq("roomid", roomid);
        } else {
            throw new SystemException("必须指定房间");
        }
        List<Aroomhourlyprices> hps = hourpriceService.list(qw);
        param.put("aroomhourlyprices", hps);

        List<Aroomdailyprices> aroomdailyprices = dailypriceService.list(qwdl);
        param.put("aroomdailyprices", aroomdailyprices);

        List<Aroommonthlyprices> aroommonthlyprices = monthlypriceService.list(qwmt);
        param.put("aroommonthlyprices", aroommonthlyprices);

        return param;
    }


    /**
     * 新增房间 老蔡
     * @param param
     * @return
     */
    public JSONObject newRoom(JSONObject param) {

        Aroom room = param.getObject("aroom", Aroom.class);

        List<Amenjin> mjs = param.getObject("mjs", new TypeReference<List<Amenjin>>() {});

        List<Aroomhourlyprices> aroomhourlyprices = param.getObject("aroomhourlyprices", new TypeReference<List<Aroomhourlyprices>>() {});

        List<Aroomdailyprices> aroomdailyprices = param.getObject("aroomdailyprices", new TypeReference<List<Aroomdailyprices>>() {});

        List<Aroommonthlyprices> aroommonthlyprices = param.getObject("aroommonthlyprices", new TypeReference<List<Aroommonthlyprices>>() {});

        room.setRoomid(StringGenerator.getID("RM"));
        roomService.save(room);

        for (Amenjin mj : mjs) {
            mj.setRoomid(room.getRoomid());
            mj.setMjid(mj.getSn());
            mj.setUid(mj.getSn());
            mj.setStoreid(room.getStoreid());
            mj.setUkey(room.getRoomid());
        }
        menjinService.saveBatch(mjs);

        for (int index = 0; index < aroomhourlyprices.size(); index++) {
            Aroomhourlyprices aroomhourlyprice = aroomhourlyprices.get(index);
            String kid = "";
            int xndex = index + 1;
            if (xndex < 10) {
                kid = "0"+xndex;
            } else {
                kid = ""+xndex;
            }
            aroomhourlyprice.setHid(new StringBuilder("HP").append(LocalDateTime.now().format(Constant.full)).append(kid).toString());
            aroomhourlyprice.setRoomid(room.getRoomid());
        }
        hourpriceService.saveBatch(aroomhourlyprices);

        if (null != aroomdailyprices && aroomdailyprices.size() > 0) {
            for (Aroomdailyprices dp : aroomdailyprices) {
                dp.setDid(StringGenerator.getID("DID"));
                dp.setRoomid(room.getRoomid());
            }
            dailypriceService.saveBatch(aroomdailyprices);
        }

        if (null != aroommonthlyprices) {
            for (Aroommonthlyprices dp : aroommonthlyprices) {
                dp.setMid(StringGenerator.getID("MID"));
                dp.setRoomid(room.getRoomid());
            }
            monthlypriceService.saveBatch(aroommonthlyprices);
        }

        param.put("aroom", room);
        param.put("mjs", mjs);
        param.put("aroomhourlyprices", aroomhourlyprices);
        param.put("aroomdailyprices", aroomdailyprices);
        param.put("aroommonthlyprices", aroommonthlyprices);

        return param;
    }

    /**
     * 修改房间 雷哥
     * @param param
     * @return
     */
    public JSONObject updateRoom(JSONObject param) {
        Aroom room = param.getObject("aroom", Aroom.class);
        if (null != room) {
            roomService.updateById(room);
        }

        // 修改门禁
        List<Amenjin> menjins = param.getObject("mjs", new TypeReference<List<Amenjin>> () {});
        if (null != menjins && menjins.size() > 1) {

            QueryWrapper<Amenjin> mjqw = new QueryWrapper<>();
            mjqw.eq("roomid", room.getRoomid());
            menjinService.remove(mjqw);
            menjinService.saveBatch(menjins);
        }

        // 时段修改
        List<Aroomhourlyprices> aroomhourlyprices = param.getObject("aroomhourlyprices", new TypeReference<List<Aroomhourlyprices>> () {});
        if (null != aroomhourlyprices && aroomhourlyprices.size() > 0) {
            QueryWrapper<Aroomhourlyprices> qwhp = new QueryWrapper<>();
            qwhp.eq("roomid", room.getRoomid());
            hourpriceService.remove(qwhp);
            for (int index = 0; index < aroomhourlyprices.size(); index++) {
                Aroomhourlyprices aroomhourlyprice = aroomhourlyprices.get(index);
                String kid = "";
                int xndex = index + 1;
                if (xndex < 10) {
                    kid = "0"+xndex;
                } else {
                    kid = ""+xndex;
                }

                if (!StringUtils.hasLength(aroomhourlyprice.getHid())) {
                    aroomhourlyprice.setHid(new StringBuilder("HP").append(LocalDateTime.now().format(Constant.full)).append(kid).toString());
                    aroomhourlyprice.setRoomid(room.getRoomid());
                }
            }
            hourpriceService.saveBatch(aroomhourlyprices);
        }

        List<Aroomdailyprices> aroomdailyprices = param.getObject("aroomdailyprices", new TypeReference<List<Aroomdailyprices>> () {});
        if (null != aroomdailyprices && aroomdailyprices.size() > 0) {

            QueryWrapper<Aroomdailyprices> qwdp = new QueryWrapper<>();
            qwdp.eq("roomid", room.getRoomid());
            dailypriceService.remove(qwdp);

            for (Aroomdailyprices dp : aroomdailyprices) {
                if (!StringUtils.hasLength(dp.getDid())) {
                    dp.setDid(StringGenerator.getID("DID"));
                    dp.setRoomid(room.getRoomid());
                }
            }
            dailypriceService.saveBatch(aroomdailyprices);
        }

        List<Aroommonthlyprices> aroommonthlyprices = param.getObject("aroommonthlyprices", new TypeReference<List<Aroommonthlyprices>> () {});
        if (null != aroommonthlyprices && aroommonthlyprices.size() > 0) {

            QueryWrapper<Aroommonthlyprices> qwmt = new QueryWrapper<>();
            qwmt.eq("roomid", room.getRoomid());
            monthlypriceService.remove(qwmt);

            for (Aroommonthlyprices dp : aroommonthlyprices) {
                if (!StringUtils.hasLength(dp.getMid())) {
                    dp.setMid(StringGenerator.getID("MID"));
                    dp.setRoomid(room.getRoomid());
                }
            }
            monthlypriceService.saveBatch(aroommonthlyprices);
        }

        return param;
    }

    /**
     * 房间分页查询 成哥
     * @param param
     * @return
     */
    public JSONObject getRooms(JSONObject param) {
        QueryWrapper<Aroom> qw = new QueryWrapper<>();

        String storeid = param.getString("storeid");
        if (StringUtils.hasLength(storeid)) {
            qw.eq("storeid", storeid);
        }

        String rname = param.getString("rname");
        if (StringUtils.hasLength(rname)) {
            qw.like("rname", rname);
        }

        String tp = param.getString("tp");
        if (StringUtils.hasLength(tp)) {
            qw.eq("tp", tp);
        }

        String func = param.getString("func");
        if (StringUtils.hasLength(func)) {
            qw.eq("func", func);
        }

        String jyms = param.getString("jyms");
        if (StringUtils.hasLength(jyms)) {
            qw.eq("jyms", jyms);
        }

        Integer mj = param.getInteger("mj");
        if (mj != null && mj > 0) {
            qw.eq("mj", mj);
        }

        Integer rnrs = param.getInteger("rnrs");
        if (rnrs != null && rnrs > 0) {
            qw.eq("rnrs", rnrs);
        }

        Integer yjds = param.getInteger("yjds");
        if (yjds != null && yjds > 0) {
            qw.eq("yjds", yjds);
        }

        Boolean flg = param.getBoolean("flg");
        if (null != flg) {
            qw.eq("flg", flg);
        }

        param.put("arooms", roomService.list(qw));

        return param;
    }

    /**
     * 房间分页查询 成哥
     * @param param
     * @return
     */
    public JSONObject getRoomsByPage(JSONObject param) {

        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        IPage<JSONObject> page = new Page<JSONObject>(current, size);

        QueryWrapper<JSONObject> qw = new QueryWrapper<>();
        String roomid = param.getString("roomid");
        if (StringUtils.hasLength(roomid)) {
            qw.eq("room.roomid", roomid);
        }

        String rname = param.getString("rname");
        if (StringUtils.hasLength(rname)) {
            qw.like("room.rname", rname);
        }

        String tp = param.getString("tp");
        if (StringUtils.hasLength(tp)) {
            qw.eq("room.tp", tp);
        }

        String func = param.getString("func");
        if (StringUtils.hasLength(func)) {
            qw.eq("room.func", func);
        }

        String jyms = param.getString("jyms");
        if (StringUtils.hasLength(jyms)) {
            qw.eq("room.jyms", jyms);
        }

        Integer mj = param.getInteger("mj");
        if (mj != null && mj > 0) {
            qw.eq("room.mj", mj);
        }

        Integer rnrs = param.getInteger("rnrs");
        if (rnrs != null && rnrs > 0) {
            qw.eq("room.rnrs", rnrs);
        }

        Integer yjds = param.getInteger("yjds");
        if (yjds != null && yjds > 0) {
            qw.eq("room.yjds", yjds);
        }

        String storeid = param.getString("storeid");
        if (StringUtils.hasLength(storeid)) {
            qw.eq("room.storeid", storeid);
        }

        String dzid = param.getString("dzid");
        if (StringUtils.hasLength(dzid)) {
            QueryWrapper<Astore> dzqw = new QueryWrapper<>();
            dzqw.eq("dzid", dzid);
            List<Astore> stores = storeService.list(dzqw);
            param.put("stores", stores);

            Set<String> mdids = new HashSet<>();
            stores.forEach(md -> {
                mdids.add(md.getStoreid());
            });

            if (mdids.size() > 0) {
                qw.in("room.storeid", mdids);
            }
        }

        Boolean flg = param.getBoolean("flg");
        if (null != flg) {
            qw.eq("md.flg", flg);
        }

        String jd = param.getString("jd");
        String wd = param.getString("wd");
        String cd = param.getString("cd");
        String st = param.getString("st");
        String et = param.getString("et");

        if (StringUtils.hasLength(st)) {
            st += ":00";
        }

        if (StringUtils.hasLength(et)) {
            et += ":00";
        }

        AroomMapper aroomMapper=
                (AroomMapper)roomService.getBaseMapper();

        if (StringUtils.hasLength(jd) && StringUtils.hasLength(wd)) {
            qw.orderByDesc("md.distance");
        }

        page = aroomMapper.getRoomWithStoreByPage(page, jd, wd, cd, st, et, qw);

        param.put("arooms", page);


        return param;
    }

    /**
     * 房间详细查询 雷哥
     * @param param
     * @return
     */
    public JSONObject getRoom(JSONObject param) {
        String roomid = param.getString("roomid");
        if (!StringUtils.hasLength(roomid)) {
            throw new SystemException("房间id必须指定");
        }

        // 房间信息
        Aroom room = roomService.getById(roomid);
        param.put("room", room);

        Astore astore = storeService.getById(room.getStoreid());
        param.put("astore", astore);

        // 房间时段价格信息
        QueryWrapper<Aroomhourlyprices> queryWrapperSD = new QueryWrapper<>();
        queryWrapperSD.eq("roomid", room.getRoomid());
        List<Aroomhourlyprices> aroomhourlyprices = hourpriceService.list(queryWrapperSD);
        param.put("aroomhourlyprices", aroomhourlyprices);

        QueryWrapper<Aroomdailyprices> qwdl = new QueryWrapper<>();
        qwdl.eq("roomid", room.getRoomid());
        List<Aroomdailyprices> aroomdailyprices = dailypriceService.list(qwdl);
        param.put("aroomdailyprices", aroomdailyprices);

        QueryWrapper<Aroommonthlyprices> qwmt = new QueryWrapper<>();
        qwmt.eq("roomid", room.getRoomid());
        List<Aroommonthlyprices> aroommonthlyprices = monthlypriceService.list(qwmt);
        param.put("aroommonthlyprices", aroommonthlyprices);

        // 门禁信息
        QueryWrapper<Amenjin> queryWrapperMJ = new QueryWrapper<>();
        queryWrapperMJ.eq("roomid", room.getRoomid());
        List<Amenjin> amenjins = menjinService.list(queryWrapperMJ);
        param.put("amenjins", amenjins);

        // 房间预约记录信息
        QueryWrapper<Aroomyyjl> queryWrapperYYJL = new QueryWrapper<>();
        queryWrapperYYJL.eq("roomid", room.getRoomid());
        queryWrapperYYJL.eq("pflg", 1);
        List<Aroomyyjl> aroomyyjls = aroomyyjlService.list(queryWrapperYYJL);
        param.put("aroomyyjls", aroomyyjls);


        QueryWrapper<Aroompj> pjqw = new QueryWrapper<>();
        pjqw.eq("roomid", roomid);

        List<Aroompj> aroompjs = roompjService.list(pjqw);
        param.put("aroompjs", aroompjs);


        // 提取教练ID列表
        List<String> jiaolianids =
                aroomyyjls.stream()
                        .map(Aroomyyjl::getJlid)
                        .limit(5L)
                        .collect(Collectors.toList());

        if (jiaolianids.isEmpty()) {
            param.put("ajiaolians", new JSONArray());
        } else {
            QueryWrapper<Ajiaolian> qwJl = new QueryWrapper<>();
            qwJl.in("jlid", jiaolianids);
            List<Ajiaolian> ajiaolians = ajiaolianService.list(qwJl);
            param.put("ajiaolians", ajiaolians);
        }

        // 课程信息
        // 当前房间预约记录所有课程
        QueryWrapper<Akechengitem> qwKcItem = new QueryWrapper<>();
        qwKcItem.select("DISTINCT(kcid)", "roomid");
        qwKcItem.eq("roomid", roomid);
        List<Akechengitem> kcitems = kechengitemService.list(qwKcItem);
        List<String> kcids =
                kcitems.stream()
                        .map(Akechengitem::getKcid)
                        .limit(4L)
                        .collect(Collectors.toList());

        if (kcids.isEmpty()) {
            param.put("akechengs", new JSONArray());
        } else {
            QueryWrapper<Akecheng> kcqw = new QueryWrapper<>();
            kcqw.in("akecheng.kcid", kcids);
            kcqw.in("akecheng.jlid", jiaolianids);

            AkechengMapper akechengMapper = (AkechengMapper) akechengService.getBaseMapper();

            param.put("akechengs", akechengMapper.getKcWithJl(kcqw));
        }

        return param;
    }

    public JSONObject getPjBypage(JSONObject param) {

        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (null == current || current < 0) {
            current = 1;
        }

        if (null == size || size < 0) {
            size = 16;
        }

        IPage<Aroompj> page = new Page<Aroompj>(current, size);

        QueryWrapper<Aroompj> qw = new QueryWrapper<>();
        String roomid = param.getString("roomid");
        if (StringUtils.hasLength(roomid)) {
            qw.eq("roomid", roomid);
        }

        page = roompjService.page(page, qw);
        param.put("aroompjs", page);

        return param;
    }

    public JSONObject getPjByList(JSONObject param) {

        QueryWrapper<Aroompj> qw = new QueryWrapper<>();
        String roomid = param.getString("roomid");
        if (StringUtils.hasLength(roomid)) {
            qw.eq("roomid", roomid);
        }
        String jlid = param.getString("jlid");
        if (StringUtils.hasLength(jlid)) {
            qw.eq("jlid", jlid);
        }
        List<Aroompj> aroompjs = roompjService.list(qw);
        param.put("aroompjs", aroompjs);

        return param;
    }

    /**
     * 评价预约记录的房间
     * @param param
     * @return
     */
    public JSONObject pjRoom(JSONObject param) {
        Aroompj aroompj = param.getObject("aroompj", Aroompj.class);
        aroompj.setRmpjid(StringGenerator.getID("RMPJ"));
        aroompj.setCt(LocalDateTime.now());
        roompjService.save(aroompj);
        param.put("aroompj", aroompj);
        return param;
    }

    public JSONObject getPjRoom(JSONObject param) {
        String rmpjid = param.getString("rmpjid");
        param.put("aroompj", roompjService.getById(rmpjid));
        return param;
    }
}
